package com.example.redis;

import org.springframework.core.convert.converter.Converter;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;

/**
 * Project:spring-boot-redis
 * <p>
 * Title:RedisObjectSerializer.java
 * <p>
 * Description:自定义序列化服务.
 * <p>
 * Copyrigth:Jiang Software LTD.co Copyright (c) 2021
 * <p>
 * 
 * @version 1.0
 * @since 1.8
 * @author jiang
 * @history 2021 jiang create
 */

public class RedisObjectSerializer implements RedisSerializer<Object> {
	// 为了进行对象和字节数组的转换，应该准备两个转换器
	private Converter<Object, byte[]> serializingConverter = new SerializingConverter();
	private Converter<byte[], Object> deserializingConverter = new DeserializingConverter();
	// 定义一个空数组
	private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];

	/**
	 * 反序列化
	 */
	@Override
	public Object deserialize(byte[] data) throws SerializationException {
		// 如果没有对象内容信息
		if (data == null || data.length == 0) {
			return null;
		}
		return this.deserializingConverter.convert(data);
	}

	/**
	 * 序列化
	 */
	@Override
	public byte[] serialize(Object obj) throws SerializationException {
		// 如果没有要序列化的对象，则返回一个空数组
		if (obj == null) {
			return EMPTY_BYTE_ARRAY;
		}
		// 将对象变为字节数组
		return this.serializingConverter.convert(obj);
	}

}
